package com.doeis.tools;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Map.Entry;

public class PropertiesHelper {
	private static Properties properties;
	private static final String fileName = "config.properties";
	static {
		try {
			properties = loadFile(fileName);
		} catch (Exception e) {
			properties = new Properties();
		}
	}

	public static void main(String[] args) {
		for (Entry<Object, Object> entry : properties.entrySet()) {
			System.out.println(entry.getKey() + "=" + entry.getValue());
		}
	}

	/**
	 * 加载配置文件
	 * 
	 * @param fileName
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @author wxy 2016年3月3日星期四中国标准时间上午11:02:02
	 */
	private static Properties loadFile(String fileName) throws FileNotFoundException, IOException {
		String file = getBasePath() + fileName;
		Properties properties = new Properties();
		FileInputStream is = new FileInputStream(file);
		properties.load(is);
		return properties;
	}

	public static String getBasePath() {
		String path = PropertiesHelper.class.getClassLoader().getResource("").getPath();
		return path;
	}

	public static String getProperty(String key) {
		return properties.getProperty(key, "");
	}

	public static String getProperty(String key, String defaultValue) {
		return properties.getProperty(key, defaultValue);
	}

	public static int getInt(String key, int defaultValue) {
		if (StringHelper.isNotNull(key) && StringHelper.isDigit(key)) {
			return Integer.parseInt(properties.getProperty(key));
		}
		return defaultValue;
	}

	public static boolean getBoolean(String key, boolean defaultValue) {
		String value = properties.getProperty(key);
		if (StringHelper.isNotNull(value)) {
			if("true".equalsIgnoreCase(key)||"1".equals(key)){
				return true;
			}
		}
		return defaultValue;
	}

	public static long getLong(String key, long defaultValue) {
		if (StringHelper.isNotNull(key) && StringHelper.isDigit(key)) {
			return Long.parseLong(properties.getProperty(key));
		}
		return defaultValue;
	}
}
